package org.kl.bf.web.basic;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.joda.time.DateTime;
import org.kl.bf.entity.basic.BasicJoinFile;
import org.kl.bf.entity.basic.CodeValues;
import org.kl.bf.entity.easyui.EasyuiUtils;
import org.kl.bf.service.basic.BasicJoinFileService;
import org.kl.bf.service.basic.CodeValuesService;
import org.kl.bf.utils.BasicConstants;
import org.kl.bf.utils.ExcelWriter;
import org.kl.bf.utils.KLServlets;
import org.kl.bf.web.base.BasicController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.web.MediaTypes;

/**
 * 系统配置
 * 
 * @Author hqm
 * @CreateTime 2014-3-13 下午9:34:36
 */
@Controller
@RequestMapping(value = "/basic/basicJoinFile")
public class BasicJoinFileController extends BasicController {
	@Autowired
	private BasicJoinFileService basicJoinFileService;
	@Autowired
	private CodeValuesService codeValuesService;

	@RequiresPermissions("basicJoinFile:list")
	@RequestMapping(method = RequestMethod.GET)
	public String list() {
		return "basic/basicJoinFileList";
	}

	@RequiresPermissions("basicJoinFile:list")
	@RequestMapping(value = "dataGrid", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String dataGrid(@RequestParam(value = "pageNumber", defaultValue = "1") int pageNumber,
			@RequestParam(value = "rows", defaultValue = PAGE_SIZE) int pageSize,
			@RequestParam(value = "sort", defaultValue = "id") String sortType,
			@RequestParam(value = "order", defaultValue = "desc") String orderType, Model model, ServletRequest request) {
		Map<String, Object> searchParams = KLServlets.getParametersStartingWith(request, SEARCH_PREFIX);
		Page<BasicJoinFile> basicJoinFiles = basicJoinFileService.getUserBasicJoinFile(searchParams, pageNumber, pageSize, sortType,
				orderType);
		return EasyuiUtils.buildEasyuiGridJsonString(basicJoinFiles.getContent(), (int) basicJoinFiles.getTotalElements());
	}

	@RequiresPermissions("basicJoinFile:export")
	@RequestMapping(value = "excelExport", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String excelExport(@RequestParam(value = "pageNumber", defaultValue = "1") int pageNumber,
			@RequestParam(value = "sort", defaultValue = "id") String sortType,
			@RequestParam(value = "order", defaultValue = "desc") String orderType, Model model, ServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> searchParams = KLServlets.getParametersStartingWith(request, SEARCH_PREFIX);
		Page<BasicJoinFile> basicJoinFiles = basicJoinFileService.getUserBasicJoinFile(searchParams, pageNumber, 0, sortType, orderType);
		try {
			// 输出Excel文件.
			response.setContentType("application/vnd.ms-excel");
			response.setHeader("Content-Disposition",
					"attachment;filename=\""
							+ new String(("系统配置" + new DateTime().toString("yyyyMMddHHmmss") + ".xls").getBytes("gb2312"), "ISO8859-1")
							+ "\"");
			ExcelWriter.exportExcel("系统配置", BasicJoinFile.class, basicJoinFiles.getContent(), response.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				response.getOutputStream().flush();
				response.getOutputStream().close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	// @RequiresPermissions("basicJoinFile:update")
	@RequestMapping(value = "update", method = RequestMethod.POST, produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String update(@Valid @ModelAttribute("basicJoinFile") BasicJoinFile basicJoinFile, BindingResult result,
			@RequestParam(value = "codeName", defaultValue = "") String codeName, HttpSession session) {
		/*if (result.hasErrors()) {
			return ajaxMsg(bindingMsg(result), false, null);
		}*/
		try {
			CodeValues businessType = codeValuesService.findByTableCodeAndCodeName(
					BasicConstants.CONFIG_FILEBUSINESSTYPE, codeName);
			if (businessType == null) {
				return ajaxMsg("上传文件失败，无法获取到附件业务类型", false, null);
			}
			basicJoinFile.setBusinessType(businessType.getCodeName());
			basicJoinFile.setInUse(0);
			basicJoinFileService.saveBasicJoinFile(basicJoinFile);
		} catch (Exception e) {
			e.printStackTrace();
			return ajaxMsg("编辑失败[" + e.getMessage() + "]", false, null);
		}
		return ajaxMsg("编辑成功", true, basicJoinFile);
	}

	@RequiresPermissions({ "basicJoinFile:delete" })
	@RequestMapping(value = "delete/{id}", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String delete(@PathVariable("id") String id, RedirectAttributes redirectAttributes, HttpSession session) {
		basicJoinFileService.deleteBasicJoinFile(id);
		return ajaxMsg("删除成功", true, null);
	}

	@RequiresPermissions({ "basicJoinFile:delete" })
	@RequestMapping(value = "multiDelete", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String multiDelete(@RequestParam(value = "ids", defaultValue = "") String ids) {
		String msg = "";
		try {
			msg = basicJoinFileService.multiDelete(ids);
		} catch (Exception e) {
			e.printStackTrace();
			return ajaxMsg("删除失败:" + e.getMessage(), false, null);
		}
		return ajaxMsg("删除成功:" + msg, true, null);
	}

	/**
	 * 所有RequestMapping方法调用前的Model准备方法, 实现Struts2
	 * Preparable二次部分绑定的效果,先根据form的id从数据库查出Task对象,再把Form提交的内容绑定到该对象上。
	 * 因为仅update()方法的form中有id属性，因此仅在update时实际执行.
	 */
	@ModelAttribute
	public void getBasicJoinFile(@RequestParam(value = "id", defaultValue = "-1") String id, Model model) {
		if (!id.equals("-1")) {
			model.addAttribute("basicJoinFile", basicJoinFileService.getBasicJoinFile(id));
		}
	}
}
